package artid.com.arttogo.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.umeng.socialize.utils.Log;

import artid.com.arttogo.R;
import artid.com.arttogo.bean.Qqlogin;
import artid.com.arttogo.bean.Sendqqcode;
import artid.com.arttogo.bean.UserItem;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.db.DataKeeper;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.utils.Config;
import artid.com.arttogo.utils.MySharedPreferences;

public class BDwxActivity extends BaseActivity implements
        OnClickListener {
    private TextView mComplete;
    private Intent mIntent;
    private TextView info, haveCode;
    private EditText meditPhone, code;
    MySharedPreferences share;
    String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_wx);
        share = MySharedPreferences.getMySharedPreferences(BDwxActivity.this);
        initView();
    }

    private void initView() {
        mContext = this;
        mBack = (ImageView) findViewById(R.id.back_btn);
        mTittle = (TextView) findViewById(R.id.tittle_text);
        haveCode = (TextView) findViewById(R.id.have_code);
        haveCode.setOnClickListener(this);
        meditPhone = (EditText) findViewById(R.id.et_pw_new);
        code = (EditText) findViewById(R.id.et_code);
        mBack.setOnClickListener(this);
        info = (TextView) findViewById(R.id.regwx_textinfo);
        mTittle.setText("绑定手机");
        mComplete = (TextView) findViewById(R.id.complete);
        mComplete.setOnClickListener(this);
        type = getIntent().getExtras().getString("type");

    }

    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            haveCode.setText((millisUntilFinished / 1000) + "秒后可重发");
            haveCode.setBackgroundResource(R.drawable.btn_hui);
            haveCode.setClickable(false);
        }

        @Override
        public void onFinish() {
            haveCode.setEnabled(true);
            haveCode.setBackgroundResource(R.drawable.btn_orange);
            haveCode.setClickable(true);
            haveCode.setText("获取验证码");

        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.complete:
                complete(type);

                break;
            //
            case R.id.back_btn:
                finish();
                break;

            case R.id.have_code:
                sendCode();
                break;
            default:
                break;
        }
    }


    void sendCode() {
        VolleyBasic.getInstance(BDwxActivity.this).post(Cache.sendqqcode,
                VolleyMap.getInstance().sendqqcode(meditPhone.getText().toString(), type), Sendqqcode.class, new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        Sendqqcode itemSendqqcode = (Sendqqcode) vd.getData();
                        if (itemSendqqcode.getState().equals(false)) {
                            info.setVisibility(View.VISIBLE);
                            info.setText("*登录密码为手机号后6位，请妥善保管。");
                        }
                        timer.start();
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub

                    }
                });
    }

    /**
     *
     */
    private void complete(String tpye) {
        // TODO Auto-generated method stub
        if (TextUtils.isEmpty(meditPhone.getText().toString())) {
            Toast.makeText(mContext, "手机号码不能为空", 2).show();
        }
        if (TextUtils.isEmpty(code.getText().toString())) {
            Toast.makeText(mContext, "验证码不能为空", 2).show();
            return;
        }
        String appsecret = share.getValue("appsecret", "");
        String headurl = share.getValue("qqheadurl", "");
        String name = share.getValue("qqname", "");
        VolleyBasic.getInstance(BDwxActivity.this).post(Cache.qqlogin2,
                VolleyMap.getInstance().qqlogin2(appsecret, tpye, meditPhone.getText().toString(),
                        headurl, name, code.getText().toString()), Qqlogin.class,
                new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        final Qqlogin Qqlogin = (Qqlogin) vd.getData();
                        Config.showTip(mContext, "注册成功！");
                        share.setValue("login", meditPhone.getText().toString());
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                //环信注册
                                try {
                                    // 调用sdk注册方法
                                    EMClient.getInstance().createAccount(AppUtil.getUser().getUid(), "yjbgp2016");
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            Log.d("log", AppUtil.getUser().getUid() + "：环信注册成功");
                                            loginHX();
                                        }
                                    });
                                } catch (HyphenateException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                    Log.d("log", AppUtil.getUser().getUid() + "：环信注册失败");
                                }
                            }
                        }).start();
                        UserItem us = new UserItem();
                        us.setHeadurl(Qqlogin.getHeadurl());
                        us.setMobile(Qqlogin.getMobile());
                        us.setRealname(Qqlogin.getRealname());
                        us.setToken(Qqlogin.getToken());
                        us.setUid(Qqlogin.getUid());
                        us.setLogin(true);
                        us.setIsQQ(Qqlogin.getQq());
                        us.setIsWx(Qqlogin.getWeixin());
                        DataKeeper.keepSerializable(mContext, us);
                        AppUtil.setUser();
                        loginHX();
                        mIntent = new Intent(mContext, MainActivity.class);
                        mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(mIntent);
                        finish();
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub

                    }
                });
    }

    private void loginHX() {
        if (!TextUtils.isEmpty(AppUtil.getUser().getUid())) {
            EMClient.getInstance().login(AppUtil.getUser().getUid(),
                    "yjbgp2016", new EMCallBack() {// 回调
                        @Override
                        public void onSuccess() {
                            Activity activity = (Activity) mContext;
                            activity.runOnUiThread(new Runnable() {
                                public void run() {
                                    Log.d("log", "环信:登陆聊天服务器成功！");
                                }
                            });
                        }

                        @Override
                        public void onProgress(int progress, String status) {
                            Log.d("log", "环信:登陆中！");
                        }

                        @Override
                        public void onError(int code, String message) {
                            Log.d("log", "环信:登陆聊天服务器失败！");
                            loginHX();
                        }
                    });
        }
    }

}
